<?php
/**
*
*===================================================================
*
*  phpBB Code Repository -- Installer File
*-------------------------------------------------------------------
*	Script info:
* Version:		2.0.0 - "Xerxes" - Alpha 1
* SVN ID:		$Id: index.php 3 2009-07-31 02:25:51Z sTraTosphere.programming $
* Copyright:	(c) 2008, 2009 | Obsidian
* Copyright:	(c) 2008, 2009 | Deadpool (original author) -- http://the-webmasters-resource.info
* License:		http://opensource.org/licenses/gpl-2.0.php | GNU Public License v2
* Package:		Install
*
*===================================================================
*
*/

/**
* Version info -
* @ignore
*/
define('CRS_VERSION', '2.0.0 Alpha 1');
define('CRS_VERSION_BIG', 'phpBB Code Repository - 2.0.0 Alpha 1');

/**
* @ignore
*/
define('IN_PHPBB', true);
define('IN_INSTALL', true);
if(!defined('INSTALLER_PATH')) define('INSTALLER_PATH', './');
if(!defined('PHPBB_ROOT_PATH')) define('PHPBB_ROOT_PATH', '../');
if(!defined('PHP_EXT')) define('PHP_EXT', substr(strrchr(__FILE__, '.'), 1));
$phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH : '../';
$phpEx = substr(strrchr(__FILE__, '.'), 1);
include(PHPBB_ROOT_PATH . 'common.' . PHP_EXT);
require(PHPBB_ROOT_PATH . 'includes/crs/constants.' . PHP_EXT);

// We want this enabled to report proper errors.
if (!defined('DEBUG'))
{
	define('DEBUG', true);
}

// Start session management
$user->session_begin();
$auth->acl($user->data);
$user->setup(array('mods/lang_crs', 'mods/lang_crs_install'));

// Load installation information...
$install = '';
$install .= 'cGhwQkIgQ29kZSBSZXBvc2l0b3J5IDxzdHJvbmcgdGl0bGU9IiUx';
$install .= 'JHMiPnYlMiRzPC9zdHJvbmc+ICZjb3B5OyAyMDA4LCAyMDA5IDxh';
$install .= 'IGhyZWY9Imh0dHA6Ly93d3cuaW5maW5pdHlob3VzZS5vcmcvIiBz';
$install .= 'dHlsZT0iZm9udC13ZWlnaHQ6IGJvbGQ7Ij5PYnNpZGlhbjwvYT4=';
build_install_info($install);

//! Don't you know who /I/ am?
if (!$user->data['is_registered'])
{
	if ($user->data['is_bot'])
	{
		redirect(append_sid(PHPBB_ROOT_PATH . 'index.' . PHP_EXT));
	}
	// Hold on, my ID has /got/ to be in here somewhere..
	login_box('', 'LOGIN');
}
else if ($user->data['user_type'] != USER_FOUNDER)
{
	//! Give them das boot out of there.  :3
	trigger_error('NOT_AUTHORIZED');
}

$mode = request_var('mode', 'overview');
$sub = request_var('sub', '');

$template->set_custom_template(INSTALLER_PATH . 'template', 'admin');
$template->assign_var('T_TEMPLATE_PATH', PHPBB_ROOT_PATH . 'adm/style');

$install = new installer();

$install->create('install', INSTALLER_PATH . 'index.' . PHP_EXT, $mode, $sub);
$install->load();

if(!defined('CRS_INSTALL_CHECKSUM') || !defined('CRS_MD5') || !defined('CRS_LOADED'))
{
	// Wuh duh ma huh ta duh fung-kwong duh wai-shung doh!
	trigger_error(base64_decode(CRS_HASHFAIL_MESSAGE), E_USER_ERROR);
}

// Generate the page
$install->page_header($install->get_page_title());
$install->generate_navigation();

$template->set_filenames(array(
	'body' => $install->get_tpl_name())
);

page_footer();

/**
 * Installer class
 * 
 * @author Obsidian
 * @copyright (c) 2008, 2009 | Obsidian
 * @license http://opensource.org/licenses/gpl-2.0.php | GNU Public License v2
 * 
 * @note: Somewhat re-used from the phpBB3 installation script
 */
class installer
{
	/**
	 * The ID...for...something...
	 * @var integer
	 */
	public $id = 0;
	
	/**
	 * The module type.
	 * @var string
	 */
	public $type = 'install';
	
	/**
	 * The modules that are available.
	 * @var array
	 */
	private $module_ary = array();
	
	/**
	 * The currently loaded module's filename.
	 * @var string
	 */
	private $filename = '';
	
	/**
	 * The URL to the installer & module
	 * @var string
	 */
	public $module_url = '';
	
	/**
	 * Current mode
	 * @var string
	 */
	private $mode = '';
	
	/**
	 * Current submode
	 * @var string
	 */
	private $sub = '';

	public function create($module_type, $module_url, $selected_mode = false, $selected_submode = false)
	{
		global $db, $config;

		$module = array();
		if(($dir = scandir(INSTALLER_PATH)) === false)
		{
			trigger_error('Unable to access the installation directory', E_USER_ERROR);
		}

		$setmodules = 1;
		foreach($dir as $file)
		{
			if (preg_match('#^install_(.*?)\.' . PHP_EXT . '$#', $file))
			{
				// Do not suppress error if in DEBUG_EXTRA mode
				$include_result = (defined('DEBUG_EXTRA')) ? (include $file) : (@include $file);
				
				if ($include_result === false)
				{
					trigger_error('Installation module file ' . $file . " couldn't be opened.", E_USER_ERROR);
				}
			}
		}

		unset($setmodules);

		if (!sizeof($module))
		{
			trigger_error('No installation modules found.', E_USER_ERROR);
		}

		// Order to use and count further if modules get assigned to the same position or not having an order
		$max_module_order = 1000;

		foreach ($module as $row)
		{

			// Module order not specified or module already assigned at this position?
			if (!isset($row['module_order']) || isset($this->module_ary[$row['module_order']]))
			{
				$row['module_order'] = $max_module_order;
				$max_module_order++;
			}

			$this->module_ary[$row['module_order']]['name'] = $row['module_title'];
			$this->module_ary[$row['module_order']]['filename'] = $row['module_filename'];
			$this->module_ary[$row['module_order']]['subs'] = $row['module_subs'];
			$this->module_ary[$row['module_order']]['stages'] = $row['module_stages'];

			if (strtolower($selected_mode) == strtolower($row['module_title']))
			{
				$this->id = (int) $row['module_order'];
				$this->filename = (string) $row['module_filename'];
				$this->module_url = (string) $module_url;
				$this->mode = (string) $selected_mode;
				// Check that the sub-mode specified is valid or set a default if not
				if (is_array($row['module_subs']))
				{
					$this->sub = strtolower((in_array(strtoupper($selected_submode), $row['module_subs'])) ? $selected_submode : $row['module_subs'][0]);
				}
				else if (is_array($row['module_stages']))
				{
					$this->sub = strtolower((in_array(strtoupper($selected_submode), $row['module_stages'])) ? $selected_submode : $row['module_stages'][0]);
				}
				else
				{
					$this->sub = '';
				}
			}
		}
	}

	/**
	* Load and run the relevant module if applicable
	*/
	public function load($mode = false, $run = true)
	{
		if ($run)
		{
			if (!empty($mode))
			{
				$this->mode = $mode;
			}

			$module = $this->filename;
			if (!class_exists($module))
			{
				trigger_error('Module "' . htmlspecialchars($module) . '" not accessible.', E_USER_ERROR);
			}
			$this->module = new $module($this);

			if (method_exists($this->module, 'main'))
			{
				$this->module->main($this->mode, $this->sub);
			}
		}
	}

	/*
	* We're using our own page_header() function as if we used the normal one you would get errors since the config values
	* Have not been created
	*/
	public function page_header($page_title)
	{
		global $db, $config, $template, $SID, $_SID, $user, $auth, $phpEx, $phpbb_root_path;

		if (defined('HEADER_INC'))
		{
			return;
		}

		define('HEADER_INC', true);

		// gzip_compression
		if ($config['gzip_compress'])
		{
			if (@extension_loaded('zlib') && !headers_sent())
			{
				ob_start('ob_gzhandler');
			}
		}

		// Which timezone?
		$tz = ($user->data['user_id'] != ANONYMOUS) ? strval(doubleval($user->data['user_timezone'])) : strval(doubleval($config['board_timezone']));

		// Send a proper content-language to the output
		$user_lang = $user->lang['USER_LANG'];
		if (strpos($user_lang, '-x-') !== false)
		{
			$user_lang = substr($user_lang, 0, strpos($user_lang, '-x-'));
		}

		$template->assign_var('PAGE_TITLE', $page_title);

		// application/xhtml+xml not used because of IE
		header('Content-type: text/html; charset=UTF-8');

		header('Cache-Control: private, no-cache="set-cookie"');
		header('Expires: 0');
		header('Pragma: no-cache');

		return;
	}

	/**
	* Returns desired template name
	*/
	public function get_tpl_name()
	{
		return $this->module->tpl_name . '.html';
	}

	/**
	* Returns the desired page title
	*/
	public function get_page_title()
	{
		global $user;

		if (!isset($this->module->page_title))
		{
			return '';
		}

		return (isset($user->lang[$this->module->page_title])) ? $user->lang[$this->module->page_title] : $this->module->page_title;
	}

	/**
	* Generate the navigation tabs
	*/
	public function generate_navigation()
	{
		global $user, $template, $phpEx;

		if (is_array($this->module_ary))
		{
			@ksort($this->module_ary);
			foreach ($this->module_ary as $cat_ary)
			{
				$cat = $cat_ary['name'];
				$l_cat = (!empty($user->lang['CAT_' . $cat])) ? $user->lang['CAT_' . $cat] : preg_replace('#_#', ' ', $cat);
				$cat = strtolower($cat);
				$url = append_sid($this->module_url . "?mode=$cat");

				if ($this->mode == $cat)
				{
					$template->assign_block_vars('t_block1', array(
						'L_TITLE'		=> $l_cat,
						'S_SELECTED'	=> true,
						'U_TITLE'		=> $url,
					));

					if (is_array($this->module_ary[$this->id]['subs']))
					{
						$subs = $this->module_ary[$this->id]['subs'];
						foreach ($subs as $option)
						{
							$l_option = (!empty($user->lang['SUB_' . $option])) ? $user->lang['SUB_' . $option] : preg_replace('#_#', ' ', $option);
							$option = strtolower($option);
							$url = append_sid($this->module_url . '?mode=' . $this->mode . "&amp;sub=$option");

							$template->assign_block_vars('l_block1', array(
								'L_TITLE'		=> $l_option,
								'S_SELECTED'	=> ($this->sub == $option),
								'U_TITLE'		=> $url,
							));
						}
					}

					if (is_array($this->module_ary[$this->id]['stages']))
					{
						$subs = $this->module_ary[$this->id]['stages'];
						$matched = false;
						foreach ($subs as $option)
						{
							$l_option = (!empty($user->lang['STAGE_' . $option])) ? $user->lang['STAGE_' . $option] : preg_replace('#_#', ' ', $option);
							$option = strtolower($option);
							$matched = ($this->sub == $option) ? true : $matched;

							$template->assign_block_vars('l_block2', array(
								'L_TITLE'		=> $l_option,
								'S_SELECTED'	=> ($this->sub == $option),
								'S_COMPLETE'	=> !$matched,
							));
						}
					}
				}
				else
				{
					$template->assign_block_vars('t_block1', array(
						'L_TITLE'		=> $l_cat,
						'S_SELECTED'	=> false,
						'U_TITLE'		=> $url,
					));
				}
			}
		}
	}
}

/**
 * Installer core class for installer module files
 * 
 * @author Obsidian
 * @copyright (c) 2008, 2009 | Obsidian
 * @license http://opensource.org/licenses/gpl-2.0.php | GNU Public License v2
 */
abstract class installer_core
{
	/**
	 * Module master function
	 * @var object
	 */
	public $p_master = NULL;
	
	/**
	 * Page title
	 * @var string
	 */
	public $page_title = '';
	
	/**
	 * Template filename
	 * @var string
	 */
	public $tpl_name = '';
	
	/**
	 * Constructor
	 */
	abstract public function __construct(&$p_master);
	
	/**
	 * Main function
	 */
	abstract public function main($mode, $sub); 
}

/**
 * Builds necessary information for the Code Repository.
 */
function build_install_info($install)
{
	global $user;
	$install = base64_decode($install);
	define('CRS_MD5', md5($install));
	if(!defined('CRS_INSTALL_CHECKSUM') || CRS_MD5 !== CRS_INSTALL_CHECKSUM)
	{
		// Wuh duh ma huh ta duh fung-kwong duh wai-shung doh!
		trigger_error(base64_decode(CRS_HASHFAIL_MESSAGE), E_USER_ERROR);
	}
	$install = sprintf($install, CRS_VERSION_BIG, CRS_VERSION);
	$user->lang['TRANSLATION_INFO'] .= (($user->lang['TRANSLATION_INFO'] != '') ? '<br />' : '') . $install;
	define('CRS_LOADED', true);
}

?>